import {
  listAllMenu,
  addMenu,
  editMenu,
  editMenuIcon,
  deleteMenu
} from '@/api/menu'

import {
  parseListAllData,
  getMenuListFromLocalStorage,
  // initRouterNode,
  setMenuListToLocalStorage
} from '@/libs/util'

export default {
  state: {
    treeMenuList: getMenuListFromLocalStorage(), // 菜单管理左侧树,
    menuList: getMenuListFromLocalStorage() || '[]'
  },
  mutations: {
    updateTreeMenulist (state, list) {
      state.treeMenuList = list
    },

    updateMenulist (state, data) {
      setMenuListToLocalStorage(data)
      state.menuList = data
      // state.showview = true
    }
  },
  getters: {},
  actions: {
    // 树list数据
    handleListAllMenu ({ state, commit }) {
      return new Promise((resolve, reject) => {
        listAllMenu()
          .then(res => {
            resolve(res)
          })
          .catch(err => {
            reject(err)
          })
      })
    },

    updateTreeMenulist ({ state, commit, rootState }, data) {
      // console.log('updateTreeMenulist', data)
      // 更新菜单管理左侧树
      if (!data) {
        return
      }
      let list = parseListAllData(data)
      commit('updateTreeMenulist', list)
    },

    // 添加菜单
    handleAddMenu ({ state, commit }, data) {
      return new Promise((resolve, reject) => {
        addMenu(data)
          .then(res => {
            resolve(res)
          })
          .catch(err => {
            reject(err)
          })
      })
    },

    // 编辑菜单
    handleEditMenu ({ state, commit }, data) {
      return new Promise((resolve, reject) => {
        editMenu(data)
          .then(res => {
            resolve(res)
          })
          .catch(err => {
            reject(err)
          })
      })
    },

    // 编辑菜单icon
    handleEditMenuIcon ({ state, commit }, data) {
      return new Promise((resolve, reject) => {
        editMenuIcon(data)
          .then(res => {
            resolve(res)
          })
          .catch(err => {
            reject(err)
          })
      })
    },

    // 删除菜单
    handleDeleteMenu ({ state, commit }, data) {
      return new Promise((resolve, reject) => {
        deleteMenu(data)
          .then(res => {
            resolve(res)
          })
          .catch(err => {
            reject(err)
          })
      })
    },

    updateMenulist ({ state, commit, rootState }, data) {
      // data 接口返回的原始数据
      // 更新面包屑数组
      if (!data) {
        return
      }
      // console.log('根据菜单生成router', list, data)
      return new Promise((resolve, reject) => {
        commit('updateMenulist', data)
        resolve(state.menuList)
      })
    }
  }
}
